<template>
  <div class="login">
    <div class="left-wrap">
      <left-view></left-view>
    </div>
    <div class="right-wrap">
      <div class="top-right-wrap">
        <div class="btn theme-btn" @click="toggleTheme">
          <i class="iconfont-sys">
            {{ isDark ? '&#xe6b5;' : '&#xe725;' }}
          </i>
        </div>
        <el-dropdown @command="changeLanguage">
          <div class="btn language-btn">
            <i class="iconfont-sys">&#xe611;</i>
          </div>
          <template #dropdown>
            <el-dropdown-menu>
              <div class="lang-btn-item">
                <el-dropdown-item command="zh">
                  <span class="menu-txt">简体中文</span>
                  <i v-if="locale === 'zh'" class="iconfont-sys">&#xe621;</i>
                </el-dropdown-item>
              </div>
              <div class="lang-btn-item">
                <el-dropdown-item command="en">
                  <span class="menu-txt">English</span>
                  <i v-if="locale === 'en'" class="iconfont-sys">&#xe621;</i>
                </el-dropdown-item>
              </div>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>

      <div class="header">
        <svg class="icon" aria-hidden="true">
          <use xlink:href="#iconsys-zhaopian-copy"></use>
        </svg>
        <h1>{{ systemName }}</h1>
      </div>

      <div class="login-wrap">
        <div class="form">
          <h3 class="title">{{ $t('login.title') }}</h3>
          <p class="sub-title">{{ $t('login.subTitle') }}</p>

          <!-- 登录方式切换 -->
          <div class="login-tabs">
            <span
              class="tab-item"
              :class="{ active: loginType === 'account' }"
              @click="loginType = 'account'"
            >
              账户密码登录
            </span>
            <span
              class="tab-item"
              :class="{ active: loginType === 'phone' }"
              @click="loginType = 'phone'"
            >
              手机号码登录
            </span>
          </div>

          <!-- 账号密码登录表单 -->
          <el-form
            v-if="loginType === 'account'"
            ref="formRef"
            :model="formData"
            :rules="rules"
            @keyup.enter="handleSubmit"
          >
            <el-form-item prop="username">
              <el-input
                :placeholder="$t('login.placeholder[0]')"
                size="large"
                v-model.trim="formData.username"
              />
            </el-form-item>
            <el-form-item prop="password">
              <el-input
                :placeholder="$t('login.placeholder[1]')"
                size="large"
                v-model.trim="formData.password"
                type="password"
                show-password
              />
            </el-form-item>
            <div class="drag-verify">
              <div class="drag-verify-content" :class="{ error: !isPassing && isClickPass }">
                <DragVerify
                  ref="dragVerify"
                  v-model:value="isPassing"
                  :width="width < 500 ? 328 : 438"
                  :text="$t('login.sliderText')"
                  textColor="var(--art-gray-800)"
                  :successText="$t('login.sliderSuccessText')"
                  :progressBarBg="getCssVariable('--el-color-primary')"
                  background="var(--art-gray-200)"
                  handlerBg="var(--art-main-bg-color)"
                  @pass="onPass"
                />
              </div>
              <p class="error-text" :class="{ 'show-error-text': !isPassing && isClickPass }">{{
                $t('login.placeholder[2]')
              }}</p>
            </div>

            <div class="forget-password">
              <el-checkbox v-model="formData.rememberPassword">{{
                $t('login.rememberPwd')
              }}</el-checkbox>
              <router-link class="custom-text" to="/forget-password">{{
                $t('login.forgetPwd')
              }}</router-link>
            </div>

            <el-button
              class="login-btn"
              size="large"
              type="primary"
              @click="handleSubmit"
              :loading="loading"
            >
              {{ $t('login.btnText') }}
            </el-button>

            <div class="footer">
              <p>
                {{ $t('login.noAccount') }}
                <router-link class="custom-text" to="/register">{{
                  $t('login.register')
                }}</router-link>
              </p>
            </div>
          </el-form>

          <!-- 手机号验证码登录表单 -->
          <el-form
            v-else
            ref="phoneFormRef"
            :model="phoneFormData"
            :rules="phoneRules"
            @keyup.enter="handlePhoneSubmit"
          >
            <el-form-item prop="phone">
              <el-input
                placeholder="请输入手机号"
                size="large"
                v-model.trim="phoneFormData.phone"
              />
            </el-form-item>

            <el-form-item prop="captcha">
              <div class="captcha-container">
                <el-input
                  placeholder="请输入图形验证码"
                  size="large"
                  v-model.trim="phoneFormData.captcha"
                />
                <canvas
                  ref="captchaCanvas"
                  width="120"
                  height="48"
                  class="captcha-img"
                  @click="generateCaptcha"
                ></canvas>
              </div>
            </el-form-item>

            <el-form-item prop="smsCode">
              <div class="sms-code-container">
                <el-input
                  placeholder="请输入短信验证码"
                  size="large"
                  v-model.trim="phoneFormData.code"
                />
                <el-button
                  :disabled="smsSending"
                  type="primary"
                  size="large"
                  @click="sendSmsCode"
                  class="sms-btn"
                >
                  {{ smsButtonText }}
                </el-button>
              </div>
            </el-form-item>

            <div class="forget-password">
              <el-checkbox v-model="phoneFormData.rememberPhone">记住手机号</el-checkbox>
            </div>

            <el-button
              class="login-btn"
              size="large"
              type="primary"
              @click="handlePhoneSubmit"
              :loading="phoneLoading"
            >
              登录
            </el-button>
          </el-form>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, computed } from 'vue'
  import { useRouter } from 'vue-router'
  import LeftView from '@/components/Pages/Login/LeftView.vue'
  import { SystemInfo } from '@/config/setting'
  import { ElMessage, ElNotification } from 'element-plus'
  import { useUserStore } from '@/store/modules/user'
  import { HOME_PAGE } from '@/router'
  import { ApiStatus } from '@/utils/http/status'
  import { UserService } from '@/api/usersApi'
  import { menuService } from '@/api/menuApi'
  import { getCssVariable } from '@/utils/utils'
  import { LanguageEnum, SystemThemeEnum } from '@/enums/appEnum'
  import { useI18n } from 'vue-i18n'
  import { useSettingStore } from '@/store/modules/setting'
  import { useWindowSize } from '@vueuse/core'
  import type { FormInstance, FormRules } from 'element-plus'
  const { t } = useI18n()


  //修改代码

  // 定义 canvas 引用
  const captchaCanvas = ref<HTMLCanvasElement | null>(null)
  const dragVerify = ref()

  // 验证码字符集（可选字母+数字）
  const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'

  // 生成随机验证码字符串
  const generateRandomCode = (): string => {
    let code = ''
    for (let i = 0; i < 4; i++) {
      code += chars.charAt(Math.floor(Math.random() * chars.length))
    }
    return code
  }

  // 存储验证码真实值（用于校验）
  const realCaptcha = ref('')

  // 生成验证码
  const generateCaptcha = () => {
    console.log('generateCaptcha执行了...')
    console.log('修改登录')
    if (!captchaCanvas.value) return

    const ctx = captchaCanvas.value.getContext('2d')
    if (!ctx) return

    // 清空画布
    ctx.clearRect(0, 0, 100, 40)

    // 设置背景色
    ctx.fillStyle = '#f0f0f0'
    ctx.fillRect(0, 0, 100, 40)

    // 设置字体样式
    ctx.font = 'bold 20px Arial'
    ctx.textBaseline = 'middle'

    // 生成随机验证码
    realCaptcha.value = generateRandomCode()

    // 绘制每个字符
    for (let i = 0; i < realCaptcha.value.length; i++) {
      const char = realCaptcha.value[i]
      const x = 20 + i * 20 + Math.random() * 10 - 5 // 随机偏移
      const y = 20 + Math.random() * 10 - 5
      const color = `rgb(${Math.random() * 100 + 100}, ${Math.random() * 100 + 100}, ${Math.random() * 100 + 100})`
      ctx.fillStyle = color
      ctx.fillText(char, x, y)
    }

    // 添加干扰线
    for (let i = 0; i < 3; i++) {
      ctx.strokeStyle = `rgba(${Math.random() * 100 + 100}, ${Math.random() * 100 + 100}, ${Math.random() * 100 + 100}, 0.5)`
      ctx.beginPath()
      ctx.moveTo(Math.random() * 100, Math.random() * 40)
      ctx.lineTo(Math.random() * 100, Math.random() * 40)
      ctx.stroke()
    }
  }

  const userStore = useUserStore()
  const router = useRouter()
  const isPassing = ref(false)
  const isClickPass = ref(false)

  const systemName = SystemInfo.name
  const formRef = ref<FormInstance>()
  const formData = reactive({
    username: SystemInfo.login.username,
    password: SystemInfo.login.password,
    rememberPassword: true
  })

  const rules = computed<FormRules>(() => ({
    username: [{ required: true, message: t('login.placeholder[0]'), trigger: 'blur' }],
    password: [{ required: true, message: t('login.placeholder[1]'), trigger: 'blur' }]
  }))

  const loading = ref(false)
  const { width } = useWindowSize()

  const store = useSettingStore()
  const isDark = computed(() => store.isDark)

  const onPass = () => {}

  const handleSubmit = async () => {
    console.log('handleSubmit执行了...')

    try {
      const res = await UserService.login({
        username: formData.username,
        password: formData.password
      })
      console.log('res:', res)

      let { code, data } = res
      console.log('code:', code)
      if (code === ApiStatus.success) {
        // 确保设置用户信息，包含ID字段
        if (data && data.platformUserId) {
          // 将platformUserId存储到localStorage中，供菜单API使用
          // localStorage.setItem('platformUserId', data.platformUserId)
          userStore.setUserInfo({
            ...data,
            id: data.platformUserId // 将platformUserId映射为id字段
          })
        } else {
          userStore.setUserInfo(data)
        }
        userStore.setLoginStatus(true)
        
        // 清除之前记录的用户ID，确保路由能够重新注册
        if ((window as any).lastRegisteredUserId) {
          delete (window as any).lastRegisteredUserId
        }
        
        showLoginSuccessNotice()
        // 菜单数据会在路由守卫中自动获取，直接跳转首页
        router.push(HOME_PAGE)
        console.log('请求成功' + res.message)
      } else {
        ElMessage.error(res.message)
        console.log('请求失败了')
      }
    } finally {
      console.log('')
      loading.value = false
    }
  }

  // 登录成功提示
  const showLoginSuccessNotice = () => {
    setTimeout(() => {
      ElNotification({
        title: t('login.success.title'),
        type: 'success',
        showClose: false,
        duration: 2500,
        zIndex: 10000,
        message: `${t('login.success.message')}, ${systemName}!`
      })
    }, 300)
  }

  // 切换语言
  const { locale } = useI18n()

  const changeLanguage = (lang: LanguageEnum) => {
    locale.value = lang
    userStore.setLanguage(lang)
  }

  // 切换主题
  import { useTheme } from '@/composables/useTheme'

  const toggleTheme = () => {
    let { LIGHT, DARK } = SystemThemeEnum
    useTheme().switchTheme(useSettingStore().systemThemeType === LIGHT ? DARK : LIGHT)
  }

  // 手机号验证码登录
  // 登录类型枚举
  const loginType = ref<'account' | 'phone'>('account')

  // 手机号登录表单数据
  const phoneFormData = reactive({
    phone: '',
    captcha: '',
    code: '',
    rememberPhone: false
  })

  // 手机号登录规则
  const phoneRules = computed<FormRules>(() => ({
    phone: [
      { required: true, message: '请输入手机号', trigger: 'blur' },
      { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
    ],
    captcha: [{ required: true, message: '请输入图形验证码', trigger: 'blur' }],
    code: [
      { required: true, message: '请输入短信验证码', trigger: 'blur' },
      { min: 6, max: 6, message: '验证码必须是6位数字', trigger: 'blur' }
    ]
  }))

  // 图形验证码图片
  // const captchaImage = ref('/api/captcha') // 假设后端接口返回 base64 或 URL

  // 短信验证码相关
  const smsSending = ref(false)
  const smsCountdown = ref(0)
  const smsButtonText = computed(() => {
    if (smsCountdown.value > 0) {
      return `${smsCountdown.value}s`
    }
    return '获取验证码'
  })

  const sendSmsCode = async () => {
    if (!phoneFormData.phone) {
      ElMessage.warning(t('login.phoneRequired'))
      return
    }

    if (smsCountdown.value > 0) return

    smsSending.value = true
    try {
      const res = await UserService.getCode({
        phone: phoneFormData.phone,
        captcha: phoneFormData.captcha
      })

      if (res.code === ApiStatus.success) {
        ElMessage.success('验证码已发送')
        startCountdown()
      } else {
        ElMessage.error(res.message)
      }
    } catch (err) {
      ElMessage.error('发送失败，请重试')
    } finally {
      smsSending.value = false
    }
  }

  const startCountdown = () => {
    smsCountdown.value = 60
    const timer = setInterval(() => {
      smsCountdown.value--
      if (smsCountdown.value <= 0) {
        clearInterval(timer)
      }
    }, 1000)
  }

  const handlePhoneSubmit = async () => {
    console.log('手机验证码登录成功了')
    console.log(phoneFormRef.value)
    if (!phoneFormRef.value) return
    console.log('我执行了')

    await phoneFormRef.value.validate(async (valid) => {
      if (valid) {
        console.log('我执行')
        // 校验图形验证码
        if (
          !phoneFormData.captcha ||
          phoneFormData.captcha.toUpperCase() !== realCaptcha.value.toUpperCase()
        ) {
          console.log(phoneFormData.captcha)
          console.log('我执行了')
          ElMessage.error('图形验证码错误')
          generateCaptcha() // 错误后刷新验证码
          return
        }
        console.log('我结束了')

        phoneLoading.value = true
        try {
          const res = await UserService.login({
            username: phoneFormData.phone,
            password: phoneFormData.code
          })

          if (res.code === ApiStatus.success) {
            // 确保设置用户信息，包含ID字段
            if (res.data && res.data.platformUserId) {
              // 将platformUserId存储到localStorage中，供菜单API使用
              localStorage.setItem('platformUserId', res.data.platformUserId)
              userStore.setUserInfo({
                ...res.data,
                id: res.data.platformUserId // 将platformUserId映射为id字段
              })
            } else {
              userStore.setUserInfo(res.data)
            }
            userStore.setLoginStatus(true)
            showLoginSuccessNotice()
            router.push(HOME_PAGE)
          } else {
            ElMessage.error(res.message)
          }
        } finally {
          phoneLoading.value = false
        }
      }
    })
  }

  // 表单引用
  const phoneFormRef = ref<FormInstance>()
  const phoneLoading = ref(false)
</script>

<style lang="scss" scoped>
  @use './index';
</style>
